package com.enjoy.redis.tx;

import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * 事务开启之前保证某个key没有被修改过
 * 才执行事务，否则不执行
 */
public class TransactionTest {

    @Test
    public void test() {
        Jedis jedis = new Jedis(new HostAndPort("192.168.126.128", 6379));
        // 使用watch
        String watchResult = jedis.watch("cc");
        if (!"OK".equals(watchResult)) {
            throw new RuntimeException("执行watch失败!");
        }
        Transaction transaction = jedis.multi();
        try {
            transaction.set("aa", "aa");
            transaction.set("bb", "bb");
            // 业务代码

            Thread.sleep(20000);
            // ...

            // 事务提交
            List<Object> execResult = transaction.exec();
            if (execResult == null) {
                throw new RuntimeException("事务无法执行,监视的key被修改");
            }
            System.out.println(execResult);
        } catch (Exception e) {
            // 队列丢弃
            transaction.discard();
            e.printStackTrace();
        } finally {
            String unwatch = jedis.unwatch();
            System.out.println(unwatch);
            jedis.close();
        }
    }

}
